<template>
  <div class="page-wrap">
    <div class="form-wrap">
      <div class="form-container">
        <div class="form-item flex flex-vertical-c">
          <layout-icon size="20" color="#666" type="icon-yonghu1"></layout-icon>
          <input class="form-input" type="number" placeholder="请输入手机号" v-model="phone" @input="inputPhone" />
        </div>
        <view class="form-item flex flex-vertical-c">
          <layout-icon type="icon-sms" size="20" color="#666"></layout-icon>
          <input @input="inputCaptcha" type="number" class="form-input flex1" name="captcha" placeholder="请输入短信验证码" />
          <div class="sendCaptcha" @click="sendCaptcha">
            <span class="text" v-if="!captchaSend">获取验证码</span><span class="text active" v-else>{{s}}s</span>
          </div>
        </view>
        <div class="form-item flex flex-vertical-c">
          <layout-icon size="20" color="#666" type="icon-mima"></layout-icon>
          <input class="form-input" type="password" placeholder="请输入密码" v-model="password" @input="inputPassword" />
        </div>
        <div class="form-item flex flex-vertical-c">
          <layout-icon size="20" color="#666" type="icon-mima"></layout-icon>
          <input class="form-input" type="password" placeholder="请确认输入密码" v-model="password2" @input="inputPassword2" />
        </div>
      </div>
      <div class="form-action  text-center">
        <div class="login-btn" @click="formSubmit">立即注册</div>
      </div>

    </div>

  </div>
</template>

<script>

import { error, modal, toast } from '@/common/fun'
import { regPhone } from '@/common/Regs'
import { validateFun } from '@/common/helper'
import Promisify from '@/common/Promisify'
import { sendSms, register } from '@/api/user'
import { pageMixin } from '@/mixins'
import LayoutIcon from '@/components/layout-icon/layout-icon'

export default {
  mixins: [pageMixin],
  components: {
    LayoutIcon


  },
  data () {
    return {
      onSend: false,
      mode: 'password',
      binbPhoneShow: false,
      bindPwdShow: false,
      pageTitle: '登录',
      setintervalInstance: null,
      phone: '',
      captcha: '',
      password: '',
      password2: '',
      s: 120,
      formCheckResult: false,
      smsid: null,
      pwd: '',
      pwdConfirm: '',
      BizId: '', // 短信标识
      captchaSend: false,
      bindPhoneTempData: null// 如果需要绑定手机，需要临时储存服务端给的信息
    }
  },
  methods: {
    // 拦截
    bindBackFn () {
      console.log('拦截返回成功了')
      if (this.binbPhoneShow) {
        // toast('请绑定手机号', 'none')
        this.$refs.phone.close()
        return
      }
      if (this.bindPwdShow) {
        uni.showModal({
          title: '操作提示',
          content: '是否跳过设置密码？',
          success: (res) => {
            if (res.confirm) uni.navigateBack()
          }
        })
        return
      }
      uni.navigateBack()
    },
    cancel () {
      uni.navigateBack()
    },
    formReset () {

    },
    minusFn () {
      if (this.s > 1) {
        this.s--
        return
      }
      clearInterval(this.setintervalInstance)
      this.captchaSend = false
    },
    async sendCaptcha () {
      if (this.onSend) return
      if (this.captchaSend) return
      if (!this.phone || !regPhone.test(this.phone)) {
        error('手机号码格式不符')
        return
      }

      this.onSend = true
      await sendSms({ phone: this.phone, type: 'register' }, { tip: '发送验证码' }).then(res => {
        this.captchaSend = true
        this.s = 120
        this.BizId = res.data
        this.setintervalInstance = setInterval(this.minusFn.bind(this), 1000)
      }).catch((err) => {
        error(err.msg || '发送验证码失败')
      })
      this.onSend = false
    },
    inputPassword (e) {
      this.password = e.detail.value
    },
    inputPassword2 (e) {
      this.password2 = e.detail.value
    },
    inputCaptcha (e) {
      this.captcha = e.detail.value
    },
    inputPhone (e) {
      this.phone = e.detail.value
    },
    async formSubmit () {
      const mode = this.mode
      const postData = { phone: this.phone }
      if (this.password != this.password2) {
        error('两次输入的密码不一致')
        return
      }
      postData.password = this.password
      postData.captcha = this.captcha
      postData.BizId = this.BizId

      const rule = {
        phone: {
          type: String,
          match: regPhone,
          required: true,
          length: 11,
          message: {
            required: '手机号必填',
            length: '手机号为长11位的字符',
            match: '手机号格式不符'
          }
        },
        captcha: {
          type: String,
          required: true,
          length: 4,
          message: {
            required: '验证码必填',
            length: '验证码长度为4'
          }
        },
        password: {
          type: String,
          required: true,
          message: {
            required: '密码必填'
          }
        },
        BizId: {
          type: String,
          required: true,
          message: {
            required: '短信回执缺失'
          }
        }
      }

      console.log(postData, rule)

      try {
        const checkRt = validateFun(postData, rule)

        if (checkRt !== true) {
          throw Error(checkRt[0] || '信息填写不符合要求')
          // this.formCheckResult = checkRt
          // this.$refs.refMsg.show()
          // return
        }

        if (this.password2 !== this.password) {
          throw Error('两次密码输入不一致')
        }

        await register(postData).catch((e) => {
          throw Error(e.msg || '注册失败')
        })
        toast('注册成功')
        setTimeout(() => {
          this.$back()
        }, 1000)
      } catch (e) {
        modal(e.message)
      }
    },
    cancelPwd () {
      uni.showModal({
        title: '操作提示',
        content: '是否跳过设置密码？',
        success: (res) => {
          if (res.confirm) {
            this.$refs.pwd.close()
            uni.navigateBack()
          }
        }
      })
    },
    async setPwd () {
      // const postData = { biz_passwd: this.pwd }
      //
      // const rule = {
      //   biz_passwd: {
      //     type: String,
      //     required: true,
      //     length: { min: 6 },
      //     use: {
      //       confimPwd: pwd => this.pwdConfirm === pwd // 校验重复密码
      //     },
      //     message: {
      //       type: '密码必须是字符串',
      //       required: '密码必填',
      //       length: '密码不得少于六位数',
      //       confimPwd: pwd => '两次密码不一致.'
      //     }
      //   }
      // }
      // const checkRt = validateFun(postData, rule)
      // if (checkRt !== true) {
      //   this.formCheckResult = checkRt
      //   return
      // }
      // await opBizInfo(postData, { tip: 'loading' }).catch(() => {})
      // this.$refs.pwd.close()
      // uni.navigateBack()
    },
    loginCall (userData) {
      this.$store.commit('SET_USER_INFO', userData.userInfo)
      setTimeout(function () {
        uni.navigateBack()
      }, 200)
    },
    async weixinlogin (e) {
      try {
        const checkSeting = await Promisify('getSetting').catch(() => {
          throw Error('获取配置失败')
        })
        // 未获得用户信息权限,需要让用户授权
        if (!checkSeting.authSetting['scope.userInfo']) {
          await Promisify('authorize', { scope: 'scope.userInfo' }).catch(() => {
            throw Error('请授权登录')
          })
        }
        const wxUserInfo = await Promisify('getUserInfo', { lang: 'zh_CN' }).catch(() => {
          throw Error('获取用户信息失败')
        })
        console.log(wxUserInfo)
        const { encryptedData, rawData, signature, userInfo, iv } = wxUserInfo
        if (!rawData) throw Error('请允许授权')
        const lp_raw_data = JSON.stringify({
          encryptedData,
          rawData: JSON.parse(rawData),
          signature,
          userInfo,
          iv
        })

        // 获取code
        const wxLoginRt = await Promisify('login').catch(() => {
          throw Error('微信login错误')
        })
        const { code: lp_code } = wxLoginRt

        // 请求接口
        console.log('snslogin data is', {
          login_method: 'wx_lp',
          lp_code,
          lp_raw_data
        })
        const { errorCode, data } = await userLogin({
          login_method: 'wx_lp',
          code: lp_code,
          lp_raw_data
        }, { tip: '登录中' }).catch((err) => {
          throw Error(err.msg || '第三方登录请求错误')
        })

        if (errorCode === 0) {
          this.loginCall(data)
        }

        // 需要绑定手机号
        if (errorCode === 88001) {
          this.bindPhoneTempData = data
          this.pageTitle = '绑定手机'
          this.binbPhoneShow = true // 设置这个之后，无法后退
          this.$refs.phone.show()
        }
      } catch (e) {
        console.log(e)
        error(e.message)
      }
    }
  },
  onUnload () {
    clearInterval(this.setintervalInstance)
  }
}
</script>
<style lang="scss" scoped>
  .page-wrap{
    position: relative;
  }

  .sendCaptcha{
    .text{
      color: #888;
      &.active{
        color: $fun-primary-color;
      }
    }
  }

  .form-wrap{
    margin: 0rpx 50rpx 0;
    .form-action{
      .login-btn{
        margin: 80rpx auto 0rpx;
        width: 582rpx;
        height: 84rpx;
        line-height: 84rpx;
        border-radius: 84rpx;
        background: $fun-primary-color;
        color: #fff;
      }
    }
    .form-container{

    }
    .form-item{
      height: 110rpx;
      padding: 0 10rpx;
      border-bottom: 1px solid #e7e7e7;
      .form-input{
        margin-left: 40rpx;
        width: 100%;
        display: block;
      }

    }
  }
</style>
